# coding: utf8
import logging as log
import uuid

import tornado

import cms_config
from app.base_controller import BaseController
from app.common import global_space
from app.models import User
from libs.util import check_param

log.basicConfig(format='[%(asctime)s] [%(filename)s]:[line:%(lineno)d] [%(levelname)s] %(message)s', level=log.INFO)


# /api/login
class Login(BaseController):

    @tornado.web.asynchronous
    def post(self):
        http = tornado.httpclient.AsyncHTTPClient()
        code = self.get_json_argument("code", '')
        param = [code]
        if check_param(param):
            return self.render_json(code=1001, msg='参数不全')
        type = self.get_json_argument("type", '0')
        if str(type) == '0':
            app_id = cms_config.app_id
            app_secret = cms_config.app_secret
        elif str(type) == '1':
            app_id = cms_config.manager_app_id
            app_secret = cms_config.manager_app_secret
        elif str(type) == '2':
            app_id = cms_config.producer_app_id
            app_secret = cms_config.producer_app_secret
        else:
            return self.render_json(code=1001, msg='参数不全')
        http.fetch(
            "https://api.weixin.qq.com/sns/jscode2session?appid={}&secret={}&js_code={}&grant_type=authorization_code".format(app_id, app_secret, code),
            callback=self.on_response)

    def on_response(self, response):
        if response.error:
            return self.render_json(code=1002, msg='系统异常')
        else:
            print(response.body)
            json = tornado.escape.json_decode(response.body)
            session = uuid.uuid1().hex

            avatar = self.get_json_argument("avatar", '')
            city = self.get_json_argument("city", '')
            country = self.get_json_argument("country", '')
            gender = self.get_json_argument("gender", 1)
            language = self.get_json_argument("language", '')
            nickname = self.get_json_argument("nickname", '')
            province = self.get_json_argument("province", '')
            # log.info(city)
            if not json.get('openid', ''):
                return self.render_json(code=1002, msg='系统异常')

            (user, r) = User.objects.update_or_create(openid=json['openid'],
                            defaults={'avatar': avatar, 'city': city,
                            'country': country, 'gender': gender, 'language': language,
                            'nickname': nickname, 'province': province, 'user_from': self.get_json_argument("type", 0)})

            user_type = self.get_json_argument("type", '0')

            if str(user_type) == '2' and user.user_state not in [2, 3]:
                return self.render_json(code=1002, msg='请联系管理员成为生产者！')

            global_space.set_session(session, {'id': user.id}, 21600)

            if str(user_type) == '1' and user.user_state != 1:
                return self.render_json(code=1002, msg='请联系管理员成为项目经理！', data={'session_id': session,'exist_mobile': (True if user.phone else False)})

            return self.render_json(data={'session_id': session,'produce_type':user.user_state, 'exist_mobile': (True if user.phone else False), 'enter_state': user.enter_state})


class SubmitEnterApplications(BaseController):
    
    def post(self):
        session_id = self.get_json_argument("session_id", '')
        type = self.get_json_argument('type', 0)
        phone = self.get_json_argument('phone', '')
        team_name = self.get_json_argument('team_name', '')
        jobs = self.get_json_argument('jobs', '')
        if check_param([session_id, type, phone]):
            return self.render_json(code=1001, msg='参数不全')
        session = global_space.very_session(session_id)
        if not session or 'id' not in session:
            return self.render_json(code=999, msg='session 失效')
        if (type == 1 and not team_name) or (type == 2 and not jobs):
            return self.render_json(code=1001, msg='参数不全')
        user = User.objects.filter(id=session['id']).first()
        if not user or user.user_from != 2:
            return self.render_json(code=999, msg='用户不存在')
        user.enter_applications = '%s|%s' % (type, team_name if type == 1 else jobs)
        user.phone = phone
        user.enter_state = 1
        user.save()
        return self.render_json(msg='申请成功！等待审核通过')

            